import os
import random
import time
import uuid

def get_cur_timestamp():
    """ 获取此刻时间的时间戳 """
    return time.time()


def get_cur_datestr():
    """ 获取此刻日期字符串，如：20170319 """
    return time.strftime("%Y%m%d", time.localtime())


def get_root_path():
    """ 获取项目根目录 """
    return os.path.join(os.path.dirname(os.path.abspath(__file__)), '..{}..{}'.format(os.path.sep, os.path.sep))


def response_json(code=1000, msg='Successful Operation', data=None):
    """
    :响应json数据
    :param code: code 1000：请求成功，code 1001：请求失败
    :param msg: 响应消息文本
    :param data: 响应数据
    """
    return {'code': code, 'msg': msg, 'data': data}


class Code:
    """ 响应消息状态码 """
    success = 1000
    failure = 1001


def get_file_ext(path):
    """
    获取文件的拓展名
    :param path: 文件路径
    :return: 返回文件拓展名
    """
    return os.path.splitext(path)[1]


def get_uuid():
    """ 生成UUID """
    return str(uuid.uuid1()).replace('-', '')


def get_random_str(length=20, base_str='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
    """ 生成随机字符串 """
    i = 0
    s = []
    while i < length:
        index = random.randint(0, len(base_str))
        s.append(base_str[index:index + 1])
        i += 1
    return ''.join(s)


def remove_path(path):
    """ 删除指定路径, 直接将数据库中的路径传入即可 """
    try:
        os.remove(os.path.join(get_root_path(), path))
    except BaseException as e:
        print(e)


def remove_paths(paths=[]):
    """ 删除多个路径 """
    root_path = get_root_path()
    for p in paths:
        try:
            os.remove(os.path.join(root_path, p))
        except BaseException as e:
            print(e)


class FileUtils(object):

    @staticmethod
    def upload(request, file_field):
        """
        上传文件
        :param request: request请求对象
        :param file_field: 文件字段名
        :return: 成功返回，上传后的文件路径，失败返回None
        """
        file = request.FILES.get(file_field, None)
        if file:
            # 文件上传默认路径
            file_upload_path = os.path.join(get_root_path(), 'uploads{}'.format(os.path.sep))
            # 以此刻日期为文件夹来存放文件,并生成UUID为文件重命名
            new_filename = get_uuid() + get_file_ext(file.name)
            file_url = os.path.join(get_cur_datestr(), new_filename)
            # 完整文件绝对路径
            file_path = os.path.join(file_upload_path, file_url)
            # 获得文件所在的文件夹，，判断文件夹是否存在，不存在则新创建文件夹
            path = os.path.dirname(file_path)
            if not os.path.exists(path):
                os.mkdir(path)
            # 写入上传文件到目标文件
            with open(file_path, 'wb+') as temp_file:
                for t in file.chunks():
                    temp_file.write(t)
            # 返回以根目录以后的部分
            return file_path.replace(get_root_path(), '').replace('\\', '/')
        return None

